import os, stat
import uuid

from werkzeug.utils import secure_filename

from application import app, db
from common.libs import Helper
from common.libs.Restful import Restful
from common.models.images import Image


class UploadService():
    @staticmethod
    def uploadByFile(file):
        resp = {'code': 200, 'msg': '', 'data': {}}
        config_upload = app.config['UPLOAD']
        filename = secure_filename(file.filename)
        ext = filename.rsplit('.', 1)[1]
        if ext not in config_upload['ext']:
            resp['code'] = 405
            resp['msg'] = '不允许的上传类型'
            return resp
        root_path = app.root_path + config_upload['prefix_path']
        if not os.path.exists(root_path):
            os.mkdir(root_path)
        file_dir = Helper.geneDatetime('%Y%m%d')
        save_dir = root_path + file_dir
        if not os.path.exists(save_dir):
            os.mkdir(save_dir)
            # 设置全部权限
            os.chmod(save_dir, stat.S_IRWXU | stat.S_IRGRP | stat.S_IRWXO)
        filename = str(uuid.uuid4()).replace('-', '') + '.' + ext
        file.save('{0}/{1}'.format(save_dir, filename))

        model_image = Image()
        model_image.file_key = file_dir + "/" + filename
        model_image.created_time = Helper.geneDatetime()
        db.session.add(model_image)
        db.session.commit()

        resp['data'] = {
            'file_key': file_dir+'/'+filename
        }
        return resp
